package br.com.d2g.realestate.controller;

import br.com.d2g.realestate.persistence.Property;
import br.com.d2g.realestate.controller.util.JsfUtil;
import br.com.d2g.realestate.controller.util.PaginationHelper;
import br.com.d2g.realestate.facade.PropertyFacade;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "propertyController")
@SessionScoped
public class PropertyController implements Serializable {

    private Property current;
    private DataModel items = null;
    @EJB
    private br.com.d2g.realestate.facade.PropertyFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String searchAddress;
    private String searchPostcode;
    private Integer searchMinNumberBathroom;
    private Integer searchMaxNumberBathroom;
    private Integer searchMinNumberBedroom;
    private Integer searchMaxNumberBedroom;
    private String searchFurnished;
    private String searchType;
    private String searchGarden;
    private Integer searchMinPrice;
    private Integer searchMaxPrice;
    private Integer searchMinSize;
    private Integer searchMaxSize;

    public PropertyController() {
    }

    public Property getSelected() {
        if (current == null) {
            current = new Property();
            selectedItemIndex = -1;
        }
        return current;
    }

    private PropertyFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    if (UserController.isClient()) {
                        //Check if the user is owner, if it's search only for 
                        try {
                            return getFacade().countSearchByCriteriaAndUser(UserController.getLoggedUserName(),
                                    searchAddress, searchPostcode, searchMinNumberBedroom, searchMaxNumberBedroom,
                                    searchMinNumberBathroom, searchMaxNumberBathroom, searchGarden, searchFurnished, getSearchMinSize(), getSearchMaxSize());

                        } catch (Exception e) {
                            JsfUtil.addErrorMessage(e, e.getMessage());
                        }
                    } else if (UserController.isOwner()) {
                        try {
                            return getFacade().countSearchByCriteriaAndUser(UserController.getLoggedUserName(),
                                    searchAddress, searchPostcode, searchMinNumberBedroom, searchMaxNumberBedroom,
                                    searchMinNumberBathroom, searchMaxNumberBathroom, searchGarden, searchFurnished, getSearchMinSize(), getSearchMaxSize());
                        } catch (Exception e) {
                            JsfUtil.addErrorMessage(e, e.getMessage());
                        }
                    }
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    if (UserController.isClient()) {
                        //Check if the user is owner, if it's search only for 
                        try {
                            return new ListDataModel(getFacade().searchByCriteriaAndUser(UserController.getLoggedUserName(),
                                    searchAddress, searchPostcode, searchMinNumberBedroom, searchMaxNumberBedroom,
                                    searchMinNumberBathroom, searchMaxNumberBathroom, searchGarden, searchFurnished, getSearchMinSize(), getSearchMaxSize(), new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));

                        } catch (Exception e) {
                            JsfUtil.addErrorMessage(e, e.getMessage());
                        }
                    } else if (UserController.isOwner()) {
                        try {
                            return new ListDataModel(getFacade().searchByCriteriaAndUser(UserController.getLoggedUserName(),
                                    searchAddress, searchPostcode, searchMinNumberBedroom, searchMaxNumberBedroom,
                                    searchMinNumberBathroom, searchMaxNumberBathroom, searchGarden, searchFurnished, getSearchMinSize(), getSearchMaxSize(), new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));

                        } catch (Exception e) {
                            JsfUtil.addErrorMessage(e, e.getMessage());
                        }
                    }



                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Property) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Property();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Property) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Property) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PropertyDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * @return the searchAddress
     */
    public String getSearchAddress() {
        return searchAddress;
    }

    /**
     * @param searchAddress the searchAddress to set
     */
    public void setSearchAddress(String searchAddress) {
        this.searchAddress = searchAddress;
    }

    /**
     * @return the searchPostcode
     */
    public String getSearchPostcode() {
        return searchPostcode;
    }

    /**
     * @param searchPostcode the searchPostcode to set
     */
    public void setSearchPostcode(String searchPostcode) {
        this.searchPostcode = searchPostcode;
    }

    /**
     * @return the searchMinNumberBathroom
     */
    public Integer getSearchMinNumberBathroom() {
        return searchMinNumberBathroom;
    }

    /**
     * @param searchMinNumberBathroom the searchMinNumberBathroom to set
     */
    public void setSearchMinNumberBathroom(Integer searchMinNumberBathroom) {
        this.searchMinNumberBathroom = searchMinNumberBathroom;
    }

    /**
     * @return the searchMaxNumberBathroom
     */
    public Integer getSearchMaxNumberBathroom() {
        return searchMaxNumberBathroom;
    }

    /**
     * @param searchMaxNumberBathroom the searchMaxNumberBathroom to set
     */
    public void setSearchMaxNumberBathroom(Integer searchMaxNumberBathroom) {
        this.searchMaxNumberBathroom = searchMaxNumberBathroom;
    }

    /**
     * @return the searchMinNumberBedroom
     */
    public Integer getSearchMinNumberBedroom() {
        return searchMinNumberBedroom;
    }

    /**
     * @param searchMinNumberBedroom the searchMinNumberBedroom to set
     */
    public void setSearchMinNumberBedroom(Integer searchMinNumberBedroom) {
        this.searchMinNumberBedroom = searchMinNumberBedroom;
    }

    /**
     * @return the searchMaxNumberBedroom
     */
    public Integer getSearchMaxNumberBedroom() {
        return searchMaxNumberBedroom;
    }

    /**
     * @param searchMaxNumberBedroom the searchMaxNumberBedroom to set
     */
    public void setSearchMaxNumberBedroom(Integer searchMaxNumberBedroom) {
        this.searchMaxNumberBedroom = searchMaxNumberBedroom;
    }

    /**
     * @return the searchFurnished
     */
    public String getSearchFurnished() {
        return searchFurnished;
    }

    /**
     * @param searchFurnished the searchFurnished to set
     */
    public void setSearchFurnished(String searchFurnished) {
        this.searchFurnished = searchFurnished;
    }

    /**
     * @return the searchType
     */
    public String getSearchType() {
        return searchType;
    }

    /**
     * @param searchType the searchType to set
     */
    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }

    /**
     * @return the searchGarden
     */
    public String getSearchGarden() {
        return searchGarden;
    }

    /**
     * @param searchGarden the searchGarden to set
     */
    public void setSearchGarden(String searchGarden) {
        this.searchGarden = searchGarden;
    }

    /**
     * @return the searchMinPrice
     */
    public Integer getSearchMinPrice() {
        return searchMinPrice;
    }

    /**
     * @param searchMinPrice the searchMinPrice to set
     */
    public void setSearchMinPrice(Integer searchMinPrice) {
        this.searchMinPrice = searchMinPrice;
    }

    /**
     * @return the searchMaxPrice
     */
    public Integer getSearchMaxPrice() {
        return searchMaxPrice;
    }

    /**
     * @param searchMaxPrice the searchMaxPrice to set
     */
    public void setSearchMaxPrice(Integer searchMaxPrice) {
        this.searchMaxPrice = searchMaxPrice;
    }

    /**
     * @return the searchMinSize
     */
    public Integer getSearchMinSize() {
        return searchMinSize;
    }

    /**
     * @param searchMinSize the searchMinSize to set
     */
    public void setSearchMinSize(Integer searchMinSize) {
        this.searchMinSize = searchMinSize;
    }

    /**
     * @return the searchMaxSize
     */
    public Integer getSearchMaxSize() {
        return searchMaxSize;
    }

    /**
     * @param searchMaxSize the searchMaxSize to set
     */
    public void setSearchMaxSize(Integer searchMaxSize) {
        this.searchMaxSize = searchMaxSize;
    }

    @FacesConverter(forClass = Property.class)
    public static class PropertyControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PropertyController controller = (PropertyController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "propertyController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Property) {
                Property o = (Property) object;
                return getStringKey(o.getIdProperty());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + PropertyController.class.getName());
            }
        }
    }
}
